The rule targets test methods that lack an assertion and consist solely of an action and, optionally, a setup.
[TestMethod]
public void Add_SingleNumber_ReturnsSameNumber()
{
var stringCalculator = new StringCalculator();
var actual = stringCalculator.Add("0");
}
Such tests only verify that the system under test does not throw any exceptions without providing any guarantees regarding the code’s behavior
under test. Those tests increase the coverage without enforcing anything on the covered code, resulting in a false sense of security.
The rule identifies a potential issue when no assertions are present in tests utilizing the following frameworks:
-
MSTest
-
NUnit
-
xUnit
-
FluentAssertions
(4.x and 5.x)
-
NFluent
-
NSubstitute
-
Moq
-
Shoudly
By enforcing the presence of assertions, this rule aims to enhance the reliability and comprehensiveness of tests by ensuring that they provide
meaningful validation of the expected behavior.
Exceptions
Test methods that include a call to a custom assertion method will not raise any issues.
How can you fix it?
To address this issue, you should include assertions to validate the expected behavior. Choose an appropriate assertion method provided by your
testing framework (such as MSTest, NUnit, xUnit) or select a suitable assertion library like FluentAssertions, NFluent, NSubstitute, Moq, or
Shouldly.
In addition to using built-in assertion methods, you also have the option to create custom assertion methods. To do this, declare an attribute
named [AssertionMethodAttribute]
and apply it to the respective method. This allows you to encapsulate specific validation logic within
your custom assertion methods without raising the issue. Here’s an example:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class CustomTestExample
{
[TestMethod]
public void Add_SingleNumber_ReturnsSameNumber()
{
var stringCalculator = new StringCalculator();
var actual = stringCalculator.Add("0");
Validator.AssertCustomEquality(0, actual); // Compliant
}
}
public static class Validator
{
[AssertionMethod]
public static void AssertCustomEquality(int expected, int actual)
{
// ...
}
}
public class AssertionMethodAttribute : Attribute { }